package stemmer;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

import net.didion.jwnl.JWNL;
import net.didion.jwnl.JWNLException;
import net.didion.jwnl.data.IndexWord;
import net.didion.jwnl.data.POS;
import net.didion.jwnl.dictionary.Dictionary;
import net.didion.jwnl.dictionary.MorphologicalProcessor;
import utility.cache.LRUCache;

public class WordnetStemmer implements Stemmer {
	
	private MorphologicalProcessor _processor;
	private LRUCache<String, String> _cache;

	public WordnetStemmer(){
		try {
			JWNL.initialize(new FileInputStream("./config/file_properties.xml"));
			_processor = Dictionary.getInstance().getMorphologicalProcessor();
			_cache = new LRUCache<String, String>(10000);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (JWNLException e) {
			e.printStackTrace();
		}
	}

	public String baseFormOf(String word) {
		String base = _cache.get(word);
		if(base!=null) return base;
		
		base = word;
		try {
			IndexWord verbIndexWord = _processor.lookupBaseForm(POS.VERB, word);
			IndexWord nounIndexWord = _processor.lookupBaseForm(POS.NOUN, word);
			IndexWord adjectiveIndexWord = _processor.lookupBaseForm(POS.ADJECTIVE, word);
			IndexWord adverbIndexWord = _processor.lookupBaseForm(POS.ADVERB, word);
			if(verbIndexWord!=null) base = verbIndexWord.getLemma();
			else if (nounIndexWord!=null) base = nounIndexWord.getLemma();
			else if (adjectiveIndexWord!=null) base = adjectiveIndexWord.getLemma();
			else if (adverbIndexWord!=null) base = adverbIndexWord.getLemma();
		} catch (JWNLException e) {
			e.printStackTrace();
		}
		_cache.put(word, base);
		return base;
	}

}
